package org.sean.framework.web.config;

import org.sean.framework.logging.Logger;
import org.sean.framework.util.GSONUtil;
import org.sean.framework.web.holder.RequestHolder;
import org.sean.framework.web.interceptor.ApiInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.springframework.web.util.ContentCachingRequestWrapper;

import java.lang.reflect.Type;

/**
 * 请求处理器
 *
 * @author xielei
 */
@ControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class RequestBodyAdviceHandler implements RequestBodyAdvice {

    private static final Logger LOG = Logger.newInstance(RequestBodyAdviceHandler.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                           Class<? extends HttpMessageConverter<?>> converterType) {
        if (ApiInterceptor.isExecuted() && RequestHolder.getRequest() instanceof ContentCachingRequestWrapper) {
            LOG.debug("Request Body : {}",
                    new String(((ContentCachingRequestWrapper) RequestHolder.getRequest()).getContentAsByteArray()));
        }
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
                                Class<? extends HttpMessageConverter<?>> converterType) {
        if (ApiInterceptor.isExecuted()) {
            LOG.debug("Request Object : {}", GSONUtil.obj2Json(body));
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
